package com.copyctrl.campus.portal.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.domain.User;
import com.copyctrl.campus.portal.dto.FriendsDTO;
import com.copyctrl.campus.portal.service.FriendsService;
import com.copyctrl.mapper.CampFriendsMapper;
import com.copyctrl.model.CampFriends;
import com.copyctrl.model.CampFriendsExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author:JH
 * @version:1.0
 */
@Service
public class FriendsServiceImpl implements FriendsService {
    @Autowired
    CampFriendsMapper mapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public int add(CampFriends friends) {
        return mapper.insert(friends);
    }

    @Override
    public int delete(int id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(CampFriends friends) {
        return mapper.updateByPrimaryKeySelective(friends);
    }

    @Override
    public List<FriendsDTO> findAll() {
        CampFriendsExample example=new CampFriendsExample();
        example.createCriteria().andIdIsNotNull();
        return mapper.selectByExample(example)
                .stream().map(friends -> {
                    String uid = friends.getUid().toString();
                    Object o = redisTemplate.opsForHash().get(RedisConstant.ID_OPENID, uid);
                    String s = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + o);
                    User user = JSONUtil.toBean(s, User.class);
                    FriendsDTO friendsDTO = BeanUtil.copyProperties(friends, FriendsDTO.class);
                    friendsDTO.setUser(user);
                    return friendsDTO;
                }).collect(Collectors.toList());
    }

    @Override
    public List<FriendsDTO> findById(int id) {
        CampFriendsExample example=new CampFriendsExample();
        example.createCriteria().andIdIsNotNull().andUidEqualTo(id);
        return mapper.selectByExample(example)
                .stream().map(friends -> {
                    String uid = friends.getUid().toString();
                    Object o = redisTemplate.opsForHash().get(RedisConstant.ID_OPENID, uid);
                    String s = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + o);
                    User user = JSONUtil.toBean(s, User.class);
                    FriendsDTO friendsDTO = BeanUtil.copyProperties(friends, FriendsDTO.class);
                    friendsDTO.setUser(user);
                    return friendsDTO;
                }).collect(Collectors.toList());
    }
}
